// 模型
const mongoose = require('mongoose')
// DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `use...
// 解决方法：https://www.jianshu.com/p/f3128e7ae3c5
// https://stackoverflow.com/questions/52572852/deprecationwarning-collection-findandmodify-is-deprecated-use-findoneandupdate
mongoose.set('useFindAndModify', false)

const schema = new mongoose.Schema({
  name: { type: String },
  // CategoryEdit中的model.parent中parent是id值，model:Object，name:"aa"，parent:"5dcd188e093d31fc216abff8",ref关联Category，
  // routes/admin/index.js中的Category代表存储分类的数据库，这里ref关联即这个数据库，然后根据objectId找到parent，把当前分类的父级分类找出来
  parent: { type: mongoose.SchemaTypes.ObjectId, ref: 'Category'}

})

//  以给定名称创建一个虚拟类型 (virtual type),具体看文档
//  虚拟值不能用于查询和字段选择，因为虚拟值不储存于 MongoDB。
//  https://mongoosejs.com/docs/guide.html#virtuals
schema.virtual('children', {
  localField: '_id',
  foreignField: 'parent',
  justOne: false,
  ref: 'Category'
})

schema.virtual('newsList', {
  localField: '_id',
  foreignField: 'categories',
  justOne: false,
  ref: 'Article'
})


module.exports = mongoose.model('Category', schema)